﻿//### MEMBER VARIABLES #############################################

var PageLayout;

var lastMessageId = new Array();
var oldLastMessageId = new Array();
var isOpen = new Array();

var outerLayout = new Array();
var innerLayout = new Array();

var chatPageWebPath = '';
var portalId = 0;
var agentHandlerUrl = '/DesktopModules/DNNspot-LiveSupport/ChatHandler.ashx';

var agentId = -1;
var isLoggedIn = false;

var sessionIds = "";

 //### PAGE LOAD ####################################################

jQuery(function () {
    loadSettings();
    applyLayout();
    getOpenSessions();
    reloadQueue();
    setupPersistentLogin();

    loginAgent();

    window.onbeforeunload = function () { logoutAgent(); };
    window.onunload = function () { logoutAgent(); };
    jQuery(window).unload(function () { logoutAgent(); });
});

//### UTILITY FUNCTIONS ############################################

String.format = function(text) {
    if (arguments.length <= 1)
        return text;

    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++)
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);

    return text;
};

//### HANDLER ACTIONS ##############################################

function closeSession(sessionId) {
    var postData = {};
    postData.Action = "CloseSession";

    postData.SessionId = sessionId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        closeSessionCallback,
        'json'
    );
}

function emailSession(sessionId) {
    var txtEmail = jQuery('#txtEmail-' + sessionId);
    var btnEmailSession = jQuery('#btnEmailSession-' + sessionId);
    
    var postData = {};
    postData.Action = "EmailSession";
    postData.SessionId = sessionId;
    postData.Email = txtEmail.val();

    txtEmail.attr('disabled', true);
    btnEmailSession.attr('disabled', true);

    jQuery.post(
        agentHandlerUrl,
        postData,
        emailSessionCallback,
        'json'
    );   
}

function getOpenSessions() {
    var postData = {};
    postData.Action = "GetOpenSessions";

    postData.AgentId = agentId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        getOpenSessionsCallback,
        'json'
    );
}

function joinSession(sessionId) {
    var postData = {};
    postData.Action = "JoinSession";

    postData.SessionId = sessionId;
    postData.AgentId = agentId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        joinSessionCallback,
        'json'
    );
}

function loginAgent() {    
    var postData = {};
    postData.Action = "LoginAgent";

    postData.AgentId = agentId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        null,
        'json'
    );
    
    isLoggedIn = true;
}

function logoutAgent() {
    if (isLoggedIn) {
        isLoggedIn = false;
        
        var postData = {};
        postData.Action = "LogoutAgent";

        postData.AgentId = agentId;

        jQuery.post(
            agentHandlerUrl,
            postData,
            null,
            'json'
        );
    }    
}

function getSelectedTabSessionId() {
    if(jQuery('div.chatContainer:visible input.sessionId').length > 0)
        return parseInt(jQuery('div.chatContainer:visible input.sessionId').val());
        
    return null;
}

function getSessionState(sessionId) {
    var postData = {};
    postData.Action = 'GetSessionState';
    postData.PortalId = portalId;
    postData.SessionId = sessionId;
    postData.MessageId = lastMessageId['id' + sessionId];

    jQuery.post(
        agentHandlerUrl,
        postData,
        getSessionStateCallback,
        'json'
    );
}

function postMessage(sessionId, messageBody, system) {
    var postData = {};
    postData.Action = 'PostMessage';
    postData.PortalId = portalId;
    postData.SessionId = sessionId;
    postData.MessageBody = messageBody;

    if (system != true)
        postData.AgentId = agentId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        postMessageCallback,
        'json'
    );
}

function reassignSession(sessionId) {
    var postData = {};
    postData.Action = "ReassignSession";
    postData.SessionId = sessionId;

    jQuery.post(
        agentHandlerUrl,
        postData,
        reassignSessionCallback,
        'json'
    );
}

function reloadQueue() {
    var postData = {};
    postData.Action = "ReloadQueue";
    postData.AgentId = agentId;
    postData.SessionIds = sessionIds;

    jQuery.post(
        agentHandlerUrl,
        postData,
        reloadQueueCallback,
        'json'
    );
}

function updateSession(sessionId) {
    var postData = {};
    postData.Action = "UpdateSession";
    postData.SessionId = sessionId;
    postData.Notes = jQuery('#txtNotes-' + sessionId).val();

    jQuery('#btnUpdate-' + sessionId).attr('disabled', true);
    
    jQuery.post(
        agentHandlerUrl,
        postData,
        updateSessionCallback,
        'json'
    );
}

//### HANDLER CALLBACKS ############################################

function closeSessionCallback(data) {
    if (data.Success) {
        var currentIndex = selectTabBySessionId(data.SessionId);
        jQuery('#divTabs').tabs('remove', currentIndex);
        isOpen['id' + data.SessionId] = false;
    }
}

function emailSessionCallback(data) {
    var txtEmail = jQuery('#txtEmail-' + data.SessionId);
    var btnEmailSession = jQuery('#btnEmailSession-' + data.SessionId);
    
    if (data.Success) txtEmail.val('');
    txtEmail.attr('disabled', false);
    btnEmailSession.attr('disabled', false);

    var notify = document.createElement('span');
    jQuery(notify).html(' ' + data.Message);

    btnEmailSession.nextAll('span').remove();
    btnEmailSession.after(notify);
}

function joinSessionCallback(data) {
    if (data.success) {
        lastMessageId['id' + data.Session.SessionId] = -1;
        isOpen['id' + data.Session.SessionId] = true;
        addSessionTab(data);

        if (!data.IsJoinedSession) {
            postMessage(data.Session.SessionId, String.format("{0} has connected.", data.Session.Agent.DisplayName), true);
            debugger;
            postMessage(data.Session.SessionId, String.format("{0}'s question: {1}", data.Session.Client.ShortName, data.Session.Question), true);
        }
    }
}

function getOpenSessionsCallback(data) {
    jQuery(data.Sessions).each(function() {
        joinSession(this.SessionId);
    });
}

function getSessionStateCallback(data) {
    var playSound = false;
    
    jQuery(data.Messages).each(appendMessages);

    jQuery(data.Messages).each(function() {
        if (this.ClientId != null)
            playSound = true;
    });

    var sessionId = data.SessionId;

    lastMessageId['id' + sessionId] = data.LastMessageId;

    if (oldLastMessageId['id' + sessionId] != lastMessageId['id' + sessionId]) {
        oldLastMessageId['id' + sessionId] = lastMessageId['id' + sessionId];

        if (jQuery('#session-' + sessionId + ':hidden').length > 0)
            jQuery('a[href="#session-' + sessionId + '"]').addClass('newMessage');

        if (playSound)
            jQuery('#audio #chat').jPlayer("play");
        
        jQuery('#transcript-' + sessionId).scrollTo('100%', 0);
    }

    if(isOpen['id' + data.SessionId])
        getSessionState(data.SessionId);
}

function postMessageCallback(data) {

}

function reassignSessionCallback(data) {
    if (data.Success) {
        var currentIndex = selectTabBySessionId(data.SessionId);
        jQuery('#divTabs').tabs('remove', currentIndex);

        lastMessageId['id' + data.SessionId] = null;
        oldLastMessageId['id' + data.SessionId] = null;
        isOpen['id' + data.SessionId] = false;

        outerLayout['session-' + data.SessionId] = null;
        innerLayout['session-' + data.SessionId] = null;
    }
}

function reloadQueueCallback(data) {
    if (data.Success) {
        jQuery('#tblSessions').flexReload();
        sessionIds = data.SessionIds;

        if (data.NewSessions && jQuery('#divSessions:hidden').length > 0)
            jQuery('a[href="#divSessions"]').addClass('newMessage');

        if (data.SessionIds != "") {            
            jQuery('#audio #queue').jPlayer("onSoundComplete", function() { this.element.jPlayer("play"); });
            jQuery('#audio #queue').jPlayer("play");
            
            window.focus();
        } else {
            jQuery('#audio #queue').jPlayer("stop");
        }
    }

    reloadQueue();
}

function updateSessionCallback(data) {
    var btnUpdate = jQuery('#btnUpdate-' + data.SessionId)
    var btnReassign = jQuery('#btnReassign-' + data.SessionId)
    
    btnUpdate.attr('disabled', false);
    
    var notify = document.createElement('span');
    jQuery(notify).html(' Update complete');

    btnReassign.nextAll('span').remove();
    btnReassign.after(notify);
    jQuery(notify).fadeOut(3000);
    
}

//### METHODS ######################################################

function addSessionTab(data) {
    var tabId = jQuery('#divTabs').tabs('length');
    var sessionId = data.Session.SessionId;
    
    // create elements
    var divChatInterface = document.createElement('div');

    var hidSessionId = document.createElement('input');
    
    var divChatContainer = document.createElement('div');
    var divTranscript = document.createElement('div');
    var divInput = document.createElement('div');
    var txtInput = document.createElement('textarea');

    var divNotesContainer = document.createElement('div');
    var divName = document.createElement('div');
    var divEmail = document.createElement('div');
    var divIp = document.createElement('div');
    var divUrlReferrer = document.createElement('div');
    var divCategory = document.createElement('div');
    var divQuestion = document.createElement('div');
    var divNotes = document.createElement('div');
    var divUpdate = document.createElement('div');
    var divEmailSession = document.createElement('div');

    var txtNotes = document.createElement('textarea');
    txtNotes.setAttribute('id', 'txtNotes-' + sessionId);
    txtNotes.setAttribute('rows', '4');
    txtNotes.setAttribute('cols', '30');

    var btnUpdate = document.createElement('input');
    btnUpdate.setAttribute('id', 'btnUpdate-' + sessionId);
    btnUpdate.setAttribute('type', 'button');
    btnUpdate.setAttribute('value', 'Update');

    var btnReassign = document.createElement('input');
    btnReassign.setAttribute('id', 'btnReassign-' + sessionId);
    btnReassign.setAttribute('type', 'button');
    btnReassign.setAttribute('value', 'Reassign');

    var txtEmail = document.createElement('input');
    txtEmail.setAttribute('id', 'txtEmail-' + sessionId);
    txtEmail.setAttribute('type', 'text');

    var btnEmailSession = document.createElement('input');
    btnEmailSession.setAttribute('id', 'btnEmailSession-' + sessionId);
    btnEmailSession.setAttribute('type', 'button');
    btnEmailSession.setAttribute('value', 'Email Session');
    
    jQuery(hidSessionId).addClass('sessionId').attr('type', 'hidden').val(sessionId);

    jQuery(divChatInterface).attr('id', 'session-' + sessionId).addClass('chatInterface');
    jQuery(divChatContainer).attr('id', 'chat-' + sessionId).addClass('chatContainer container outer-center');
    jQuery(divNotesContainer).attr('id', 'notes-' + sessionId).addClass('notesContainer outer-east');
    jQuery(divTranscript).attr('id', 'transcript-' + sessionId).addClass('transcript inner-center');
    jQuery(divInput).attr('id', 'input-' + sessionId).addClass('input inner-south');
    jQuery(txtInput).addClass('textarea');

    //#########################
    // nest elements
    
    //-- main
    divChatContainer.appendChild(hidSessionId);
    divChatInterface.appendChild(divChatContainer);
    divChatInterface.appendChild(divNotesContainer);
    
    //-- chat
    divChatContainer.appendChild(divTranscript);
    divChatContainer.appendChild(divInput);
    divInput.appendChild(txtInput);

    //-- notes
    divNotesContainer.appendChild(divName);
    divNotesContainer.appendChild(divEmail);
    divNotesContainer.appendChild(divIp);
    divNotesContainer.appendChild(divUrlReferrer);
    divNotesContainer.appendChild(divCategory);
    divNotesContainer.appendChild(divQuestion);
    divNotesContainer.appendChild(divNotes);
    divNotesContainer.appendChild(divUpdate);
    divNotesContainer.appendChild(divEmailSession);

    divNotes.appendChild(txtNotes);
    divUpdate.appendChild(btnUpdate);
    divUpdate.appendChild(btnReassign);

    divEmailSession.appendChild(txtEmail);
    divEmailSession.appendChild(btnEmailSession);

    jQuery(divName).html(String.format("<span class='label'>Name:</span>{0}", data.Session.Client.FullName));
    jQuery(divEmail).html(String.format("<span class='label'>Email:</span>{0}", data.Session.Client.Email));
    jQuery(divIp).html(String.format("<span class='label'>Ip:</span>{0}", data.Session.Client.Ip));
    jQuery(divUrlReferrer).html(String.format("<span class='label'>Referrer:</span>{0}", data.Session.UrlReferrer));
    jQuery(divCategory).html(String.format("<span class='label'>Category:</span>{0}", data.Session.CategoryName));
    jQuery(divQuestion).html(String.format("<span class='label'>Question:</span>{0}", data.Session.Question));
    jQuery(txtNotes).val(data.Session.Notes);

    jQuery(divNotes).prepend("<span class='label'>Notes:</span>");
    jQuery(divUpdate).prepend("<span class='label'>&nbsp;</span>");
    jQuery(divEmailSession).prepend("<br /><span class='label'>&nbsp;</span>");

    jQuery(btnUpdate).click(function() {
        updateSession(sessionId);
    });

    jQuery(btnReassign).click(function() {
        var reassign = confirm('Are you sure you want to reassign this session?');

        if (reassign) {
            reassignSession(sessionId);
        }
    });

    jQuery(btnEmailSession).click(function() {
        emailSession(sessionId);
    });
    
    // start callbacks
    getSessionState(sessionId);

    // bind elements
    jQuery(txtInput).keypress(function(e) {
        if (e.keyCode == 13) {
            e.stopPropagation();
            e.preventDefault();

            if (jQuery(this).val() != '') {
                postMessage(sessionId, jQuery(this).val());
                jQuery(this).val('');
            }
        }
    });

    // add tab
    
    var tabLabel = String.format('{0} <a class="tabClose ui-icon ui-icon-circle-close" title="Close chat session" onclick="closeTab({1})">close</a>',
        data.Session.Client.FullName,
        data.Session.SessionId);
      
    jQuery('#divTabs').append(divChatInterface);
    jQuery('#divTabs').tabs('add', '#session-' + sessionId, tabLabel);
    jQuery('#session-' + sessionId).appendTo('#divTabPanes');
    jQuery('#divTabs').tabs('select', '#session-' + sessionId);

    // setup layout
    outerLayout['session-' + sessionId] = jQuery(divChatInterface).layout({
        resizeWithWindow: false,
        center__paneSelector: '.outer-center',
        east__paneSelector: '.outer-east',
        east__closable: true,
        east__resizable: true,
        east__padding: 0,
        east__size: '50%',
        center__onresize: function() {
            innerLayout['session-' + sessionId].resizeAll();
        }
    });

    innerLayout['session-' + sessionId] = jQuery(divChatContainer).layout({
        resizeWithWindow: false,
        center__paneSelector: '.inner-center',
        south__paneSelector: '.inner-south',
        south__closable: false,
        south__resizable: false,
        south__size: 75
    });
}

function appendMessages(i, obj) {
    var msgCount = jQuery('.message').length;

    if (obj.MessageId > lastMessageId['id' + obj.SessionId]) {
        var msg = String.format('<div class="message{0}{1}"><div class="name">{2}</div><div class="body">{3}</div></div>',
        msgCount % 2 == 0 ? '' : ' alt',
        obj.ClientId == null ? (obj.AgentId == null ? ' system' : ' self') : '',
		obj.Name != null ? String.format('{0}:', obj.Name) : '',
		obj.Body);

        jQuery('#transcript-'+obj.SessionId).append(msg).autolink();
    }
}

function applyLayout() {
    jQuery(window).resize(resizeLayout);

    bindWindowKeys();

    jQuery('#audio #queue').jPlayer({ swfPath: "flash", ready: function() { this.element.jPlayer("setFile", String.format("{0}audio/queue.mp3", chatPageWebPath)) } });
    jQuery('#audio #chat').jPlayer({ swfPath: "flash", ready: function() { this.element.jPlayer("setFile", String.format("{0}audio/chat.mp3", chatPageWebPath)) } });
    
    jQuery('#divTabs').tabs({ show: tabShow });

    jQuery("#tblSessions").flexigrid({
        url: String.format('{0}QueueHandler.ashx?portalId={1}', chatPageWebPath, portalId),
        dataType: 'json',
        colModel: [
            { display: 'Open Date', sortable: false, width: 150 },
            { display: 'Client Name', sortable: false, width: 150 },
            { display: 'Category', sortable: false, width: 200 },
            { display: 'Notes', sortable: false, width: 250 }
        ],
        buttons: [
            { name: 'Join', bclass: 'add', onpress: btnJoin_Click }
        ],
        usepager: false,
        singleSelect: true,
        width: 'auto'
    });
}

function bindWindowKeys() {
    jQuery(document).bind('keydown', 'Ctrl+tab', nextTab);
    jQuery(document).bind('keydown', 'Ctrl+Shift+tab', prevTab);
    jQuery(document).bind('keydown', 'Ctrl+w', function() { closeTab(); });
}

function closeTab(sessionId) {
    if (sessionId == null)
        sessionId = getSelectedTabSessionId();

    if (sessionId != null) {
        var currentIndex = selectTabBySessionId(sessionId);

        var close = confirm('Are you sure you want to close this session?');
        
        if(close) closeSession(sessionId);
    }
}

function loadSettings() {
    chatPageWebPath = jQuery('#hidChatPageWebPath').val()
    agentHandlerUrl = String.format('{0}ChatHandler.ashx', jQuery('#hidChatPageWebPath').val());
    agentId = parseInt(jQuery('#hidAgentId').val());
    ip = jQuery('#hidIp').val();
    portalId = parseInt(jQuery('#hidPortalId').val());
    userId = parseInt(jQuery('#hidUserId').val());
}

function nextTab(event) {
    var tabCount = jQuery('#divTabs').tabs('length');
    var currentIndex = jQuery('#divTabs').tabs('option', 'selected');
    var nextIndex = (currentIndex + 1) % tabCount;

    jQuery('#divTabs').tabs('select', nextIndex);
}

function prevTab(event) {
    var tabCount = jQuery('#divTabs').tabs('length');
    var currentIndex = jQuery('#divTabs').tabs('option', 'selected');
    var prevIndex = (currentIndex - 1 + tabCount) % tabCount;

    jQuery('#divTabs').tabs('select', prevIndex);
}

function resizeLayout() {
    jQuery('div.chatInterface:visible').each(function() {
        if (outerLayout[this.id] != null)
            outerLayout[this.id].resizeAll();
    });
}

function selectTabBySessionId(sessionId) {
    jQuery('#divTabs').tabs('select', '#session-' + sessionId);
    
    return jQuery('#divTabs').tabs('option', 'selected'); 
}

function setClientId(id) {
    clientId = id;
    jQuery.cookie('DNNspotLiveChatClientId', clientId);
}

function setupPersistentLogin() {
    setInterval('jQuery("#persistentLogin").attr("src", "/");', 1000 * 60 * 5);
}

function setupPrerequisiteValidation() {
    jQuery('#divQuestions').validationEngine();
}

function showPrerequisites() {
    jQuery('#divQuestions').show();
    jQuery('body').block({
        message: jQuery('#divQuestions'),
        css: {
            cursor: 'default',
            padding: '10px',
            textAlign: 'left',
            width: '80%',
            '-moz-border-radius': '10px',
            '-webkit-border-radius': '10px'
        },
        overlayCSS: {
            cursor: 'default'
        }
    });
}

function tabSelect(event, ui) {
    
}

function tabLoad(event, ui) {

}

function tabShow(event, ui) {
    resizeLayout();
    jQuery(ui.tab).removeClass('newMessage');
    jQuery('#input-' + getSelectedTabSessionId() + ' textarea').focus();
}

//### BINDINGS #####################################################

function btnContinue_Click() {
    if (jQuery("#divQuestions").validationEngine({ returnIsValid: true })) {
        firstName = jQuery('#txtFirstName').val();
        lastName = jQuery('#txtLastName').val();
        email = jQuery('#txtEmail').val();
        categoryId = jQuery('#ddlCategories').val();
        question = jQuery('#txtQuestion').val();

        createSession();
    }
}

function txtInput_KeyPress(e) {
    if (e.keyCode == 13) {
        e.stopPropagation();
        e.preventDefault();

        if (jQuery('#txtInput').val() != '') {
            postMessage(jQuery('#txtInput').val());
            jQuery('#txtInput').val('');
        }
    }
}

function btnJoin_Click(com, grid) {
    if (com == 'Join') {
        if (jQuery('.trSelected', grid).length > 0) {
            var sessionId = jQuery('.trSelected', grid)[0].id.substr(3);
            joinSession(sessionId)
        } else {
            alert('Please select a session to join.');
        }
    }
}

//### CHAT CLASS ###################################################

function Chat() {

}